
var network = require("../../utils/NetWorkUtils.js")
var app = getApp()

var valHandle;  //答题定时器
var waitingHandle // 等待计时器
const ctx = wx.createCanvasContext("bgCanvas")
var screenWidth = wx.getSystemInfoSync().windowWidth
var animation
// pages/answer/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isWaiting:true,   //是否是等待页面
    waitingTime: 3,    //等待时间
    stepText: 5,
    question:"",
    countdown:0,
    isActiveA:false,
    isCorrect:false,
    isActiveB:false,
    isdisables:false,
    nickName:"",
    headImage:"",
    shareSuccess:false,
    rightAnswer:"0",
    coin:'',
    now:0,
    right:'',
    max:'',
    rightAnswerA:0,
    rightAnswerB:0,
    isFinished:false,
    getCoin:0,
    isHidden:true,
    moveData:null,
    answer_coin:'',
    radarImg:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
    this.setUserInformation();
    this.waitingTimeStart();
    this.requestQuestition();
    animation = wx.createAnimation({
      duration: 1000
    });
  },

  //设计头像
  setUserInformation: function () {
    this.headImage = app.globalData.avatarUrl;
    this.nickName = app.globalData.userNmae;
    this.setData({
      headImage: app.globalData.avatarUrl,
      nickName: app.globalData.userNmae
    })
  },

//继续回答问题
  _continueAnswer: function () {
    var that = this;
    that.alertview = that.selectComponent("#alertview");
    that.alertview.hideAlertView();
    that.setData({
      radarImg:null
    });
    var requestData = {
      exam_id: that.question.data.data.exam_id,
      question_id: that.question.data.data.question_id,
      num: that.question.data.data.num
    }
    network.requestHttp("m=api&c=Index&a=sharetoanswer", requestData, function (res) {
      that.question = res;
      if (res.data.state == 1) {
        that.resetAnswerStatus();
        that.question = res;
        that.setData({
          question: res,
          max: res.data.data.max,
          now: res.data.data.now,
          coin: res.data.data.coin,
          right: res.data.data.right
        })
        that.clickStartBtn();
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    return {
      title: '我正在答题赚钱，免费兑换商品，快来和我一起抢！',
      path: 'pages/index/index',
      imageUrl: '../../images/share_pic.jpg'
    }
  },

  /**
   * 
   *等待
   */
   waitingTimeStart:function (){
     var that = this;
     waitingHandle = setInterval(function () {
       if (that.data.waitingTime == 1) {
         clearInterval(waitingHandle)  //销毁定时器
         that.setData({
           isWaiting: false
         });
         if(that.question)
         {
           that.setData({
             question: that.question,
             countdown: that.question.data.data.countdown,
             max: that.question.data.data.max,
             now: that.question.data.data.now,
             coin: that.question.data.data.coin,
             right: that.question.data.data.right,
             answer_coin: that.question.data.data.answer_coin

           });
          
           that.clickStartBtn();
         }
       }else{
         that.data.waitingTime--;
         that.setData({
           waitingTime: that.data.waitingTime
         })
       }
     },1000)
   },

  /*
  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  onReady: function () {
    ctx.setLineWidth(6)
    var sizeWidth = (screenWidth/375);
    ctx.arc(30 * sizeWidth, 30 * sizeWidth, 23 * sizeWidth, 0, 2 * Math.PI)
    ctx.setStrokeStyle('#ffaaab')
    ctx.stroke()
    ctx.beginPath()
    ctx.setLineCap('round')
    ctx.setLineWidth(6)
    ctx.arc(30 * sizeWidth, 30 * sizeWidth, 23 * sizeWidth,  1.5 * Math.PI, -0.5 * Math.PI, true)
    ctx.setStrokeStyle('#ff4849')
    ctx.stroke()
    ctx.draw()
  },


  //点击开始倒计时按钮
  clickStartBtn: function () {
    var that = this
    that.data.stepText = that.data.countdown; //重新设置一遍初始值，防止初始值被改变
    var step = that.data.stepText;  //定义倒计时
    var num = -0.5;
    var decNum = 2 / step / 10
    clearInterval(valHandle)
    function drawArc(endAngle) {
      var sizeWidth = (screenWidth / 375);
      ctx.setLineWidth(6)
      ctx.arc(30 * sizeWidth, 30 * sizeWidth, 23 * sizeWidth,  0, 2 * Math.PI)
      ctx.setStrokeStyle('#ffaaab')
      ctx.stroke()
      ctx.beginPath()
      ctx.setLineCap('round')
      ctx.setLineWidth(6)
      ctx.arc(30 * sizeWidth, 30 * sizeWidth, 23 * sizeWidth, 1.5 * Math.PI, endAngle, true)
      ctx.setStrokeStyle('#ff4849')
      ctx.stroke()
      ctx.draw()
    }
    valHandle = setInterval(function () {
      that.setData({
        stepText: Math.ceil(step)
      })
      step = (step - 0.1).toFixed(1)
      num += decNum
      drawArc(num * Math.PI)
      if (step <= 0) {
        that.setData({
          stepText: Math.ceil(0)
        })
        clearInterval(valHandle)  //销毁定时器
        that.isdisables = true;
        that.requestNextQuestition();
      }
    }, 100)
  },

  //请求第一题
  requestQuestition:function(){
    var that = this;
    var requestData = {}
    network.requestHttp("m=api&c=Index&a=answerstart", requestData, function (res) {
      that.question = res;
      that.coin = res.data.data.coin;
      that.max = res.data.data.max;
      that.now = res.data.data.now;
      that.right = res.data.data.right;
      that.answer_coin = res.data.data.answer_coin;
      console.log(res);
      if(that.isWaiting == false)
      {
        that.setData({
          question: res,
          countdown: res.data.data.countdown,
          max: res.data.data.max,
          now: res.data.data.now,
          coin: res.data.data.coin,
          right: res.data.data.right,
          answer_coin: res.data.data.answer_coin
        });
      

        that.clickStartBtn();
      }
    }) 
  },

//请求下一题
  requestNextQuestition: function (res) {
    var that = this;
    var requestData = {
      exam_id: that.question.data.data.exam_id,
      question_id: that.question.data.data.question_id,
      num: that.question.data.data.num
    }
    console.log(requestData);
    if (res) {
      requestData["answer"] = res;
    }
    network.requestHttp("m=api&c=Index&a=answernext", requestData, function (res) {
      console.log(requestData);

      if (res.data.state != 1 && res.data.state != 3 && res.data.state != 4)
      {
        wx.showToast({
          title: res.data.msg,
          icon:none
        })
        return;
      }


      that.rightAnswer = res.data.data.true;
      that.isCorrect = false;
      if (res.data.state == 1 || res.data.state == 3)
      {
        if(that.rightAnswer == "1" &&that.isActiveA)
        {
          that.rightAnswerA = 1;
          that.rightAnswerB = 0;
          that.isCorrect = true;
          that.answerCorrect();

        } else  if (that.rightAnswer == "2" && that.isActiveB) {
          that.rightAnswerA = 0;
          that.rightAnswerB = 1;
          that.isCorrect = true;
          that.answerCorrect();

        }
        if(that.isActiveA == false && that.isActiveB == false)
        {
          that.isCorrect = true
          if (that.rightAnswer == "1") {
            that.isActiveA = true;
            that.isActiveB = false;
            that.rightAnswerA = true;
            that.rightAnswerB = true;

          } else {
            that.isActiveA = false;
            that.isActiveB = true;
            that.rightAnswerA = true;
            that.rightAnswerB = true;

          }
        }else
        {
          if (!that.isCorrect) {
            that.isActiveA = !that.isActiveA;
            that.isActiveB = !that.isActiveB;
          }
        }
       

        that.max = res.data.data.max;
        that.now = res.data.data.now;
        that.coin = res.data.data.coin;
        that.right = res.data.data.right;
        let a = that.rightAnswerA;
        let b = that.rightAnswerB;
        that.setData({
          rightAnswer:res.data.data.true,
          max: res.data.data.max,
          now: res.data.data.now,
          coin: res.data.data.coin,
          right: res.data.data.right,
          rightAnswerA: a,
          rightAnswerB: b,
          isActiveB: that.isActiveB,
          isActiveA :that.isActiveA,
          isCorrect: that.isCorrect
      })

        if (res.data.state == 1 ) {
          setTimeout(function () {
            that.clickStartBtn();
            that.resetAnswerStatus();
            that.question = res;
            that.setData({
              question: res,
              rightAnswer: "0",
              isHidden: true
            })
          }, 1000)
        }else
        {
          setTimeout(function () {
            that.setData({
              getCoin: res.data.data.get,
                isFinished:true
            })
          }, 1000)
        }
    } else {

        that.rightAnswer = res.data.data.true;
        if(that.isActiveA || that.isActiveB)
        {
          that.isActiveA = !that.isActiveA;
          that.isActiveB = !that.isActiveB;
          that.isCorrect = false
        }else {
          that.isCorrect = true
          if (that.rightAnswer =="1")
          {
            that.isActiveA = true;
            that.isActiveB = false;
            that.rightAnswerA = true;
            that.rightAnswerB = true;

          }else
          {
            that.isActiveA = false;
            that.isActiveB = true;
            that.rightAnswerA = true;
            that.rightAnswerB = true;
          }
        }
  
        that.setData({
          rightAnswerA: that.rightAnswerA,
          rightAnswerB: that.rightAnswerB,
          isActiveB: that.isActiveB,
          isActiveA: that.isActiveA,
          isCorrect: that.isCorrect,
          rightAnswer:that.rightAnswer
        })
        that.handleCanvarToImg();
        setTimeout(function () {
          that.alertview = that.selectComponent("#alertview");
          that.alertview.showAlertView();
          that.setData({ radarImg: that.radarImg });
        }, 1000)
    }
    })
  },

  answerCorrect:function(){
    var that = this;
    that.setData({
      isHidden: false
    })
    animation.opacity(1).translateY(0).step({ duration: 0 });
    that.setData({
      moveData: animation.export()
    })
    animation.opacity(0).translateY(-100).step();
    setTimeout(function () {
      that.setData({
        moveData: animation.export(),
      })
    }, 200)
  },
  //回答问题
  answerQuestion: function (event){
  var answer = event.currentTarget.dataset.answer
    if(this.isdisables)
    {
      return;
    }
    this.isdisables = true;
    if(answer == "1")
    {
      this.isActiveA = true;
      this.rightAnswerA = 1;
      this.rightAnswerB = 0;
      this.isActiveB = false;


    }else
    {
      this.isActiveB = true;
      this.rightAnswerB = 1;
      this.rightAnswerA = 0;
      this.isActiveA = false;

    }
    clearInterval(valHandle)  //销毁定时器
    this.requestNextQuestition(answer);
  },

  // 重新答题
  _resetStartAnswer:function(){
    wx.navigateBack({
      
    })
  },
  _shareButton:function(){
    this.shareSuccess = true;
    this.alertview = this.selectComponent("#alertview");
    this.alertview.hideAlertView();
    this.setData({
      radarImg:null
    });
    this.ShareRequestQuestition();

  },
  resetAnswerStatus:function()
  {
    this.isdisables = false;
    this.isActiveA = false;
    this.isActiveB = false;
    this.rightAnswerA = 0;
    this.rightAnswerB = 0;
    this.isCorrect = false;
    this.setData({
      isActiveA: false,
      isActiveB: false,
      rightAnswerA:0,
      rightAnswerB:0,
      isCorrect:false
  })
  },

  handleCanvarToImg:function() {
    var that = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 120,
      height: 120,
      canvasId: 'bgCanvas',
      success: function (res) {
        that.radarImg = res.tempFilePath;
      }
    });
  },
})